package cn.edu.baiyunu.myapplication.ui.create

import android.Manifest
import android.graphics.Bitmap
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import cn.edu.baiyunu.myapplication.ui.components.CreateTopAppBar
import cn.edu.baiyunu.myapplication.ui.create.components.CameraPreviewContent
import cn.edu.baiyunu.myapplication.ui.create.components.PhotoPreviewContent
import cn.edu.baiyunu.myapplication.ui.create.components.PhotoSelectionContent
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 作品创作页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateScreen(
    onNavigateUp: () -> Unit,
    navigateToSuccess: () -> Unit,
    navigateToEdit: (Uri) -> Unit = {},
    viewModel: CreateViewModel = viewModel()
) {
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    
    val screenState by viewModel.screenState.collectAsState()
    val selectedImageUri by viewModel.selectedImageUri.collectAsState()
    val capturedBitmap by viewModel.capturedBitmap.collectAsState()
    val snackbarMessage by viewModel.snackbarMessage.collectAsState()
    
    // 相机权限
    val cameraPermissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            viewModel.setScreenState(CreateViewModel.CreateScreenState.CameraPreview)
        } else {
            viewModel.showSnackbar("需要相机权限才能拍照")
        }
    }
    
    // 图片选择器
    val imagePickerLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let { viewModel.setSelectedImageUri(it) }
    }
    
    // 提示消息
    LaunchedEffect(snackbarMessage) {
        snackbarMessage?.let {
            snackbarHostState.showSnackbar(it)
        }
    }
    
    // 成功处理后的操作
    LaunchedEffect(screenState) {
        if (screenState is CreateViewModel.CreateScreenState.Success) {
            navigateToSuccess()
        }
    }
    
    Scaffold(
        topBar = {
            CreateTopAppBar(
                title = "创作",
                onNavigateUp = onNavigateUp,
                showHelpAction = true,
                onHelpClick = { viewModel.showSnackbar("创作页面帮助") }
            )
        },
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            when (screenState) {
                CreateViewModel.CreateScreenState.Initial, 
                CreateViewModel.CreateScreenState.PhotoSelection -> {
                    PhotoSelectionContent(
                        isDragging = viewModel.isDragging,
                        onDragStateChanged = viewModel::updateDraggingState,
                        onSelectImage = { imagePickerLauncher.launch("image/*") },
                        onCameraClick = {
                            cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
                        }
                    )
                }
                
                CreateViewModel.CreateScreenState.CameraPreview -> {
                    CameraPreviewContent(
                        onImageCaptured = { bitmap ->
                            viewModel.setCapturedBitmap(bitmap)
                        },
                        onCancel = {
                            viewModel.setScreenState(CreateViewModel.CreateScreenState.PhotoSelection)
                        }
                    )
                }
                
                CreateViewModel.CreateScreenState.PhotoPreview -> {
                    PhotoPreviewContent(
                        bitmap = capturedBitmap,
                        imageUri = selectedImageUri,
                        isProcessing = viewModel.isProcessing,
                        onDelete = {
                            viewModel.clearImage()
                        },
                        onReUpload = {
                            viewModel.clearImage()
                        },
                        onUsePhoto = {
                            if (navigateToEdit != {}) {
                                // 导航到编辑页面而不是处理作品
                                selectedImageUri?.let { navigateToEdit(it) } ?: run {
                                    // 如果没有URI但有bitmap，先保存bitmap
                                    capturedBitmap?.let { bitmap ->
                                        viewModel.saveBitmapToFile(context, bitmap)?.let { file ->
                                            navigateToEdit(Uri.fromFile(file))
                                        } ?: run {
                                            viewModel.showSnackbar("无法保存照片，请重试")
                                        }
                                    } ?: run {
                                        viewModel.showSnackbar("请先选择或拍摄照片")
                                    }
                                }
                            } else {
                                // 如果没有提供编辑导航，显示提示并处理
                                viewModel.showSnackbar("正在处理照片...")
                                // 使用processArtwork函数处理，它会自动设置处理状态
                                viewModel.processArtwork {
                                    // 处理完成后会自动调用navigateToSuccess
                                }
                            }
                        }
                    )
                }
                
                else -> { /* 其他状态不处理 */ }
            }
        }
    }
} 